<?php

namespace Gds\UserBundle\Listener;

use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\Bundle\DoctrineBundle\Registry as Doctrine; // for Symfony 2.1.0+

// use Symfony\Bundle\DoctrineBundle\Registry as Doctrine; // for Symfony 2.0.x

/**
 * Custom login listener.
 */
class LoginListener {

    /** @var \Symfony\Component\Security\Core\SecurityContext */
    private $securityContext;

    /** @var \Doctrine\ORM\EntityManager */
    private $em;
    private $container;

    /**
     * Constructor
     *
     * @param SecurityContext $securityContext
     * @param Doctrine $doctrine
     */
    public function __construct(SecurityContext $securityContext, Doctrine $doctrine,ContainerInterface $container) {
        
        $this->securityContext = $securityContext;
        $this->em = $doctrine->getEntityManager();
        $this->container=$container;
        
    }

    /**
     * Do the magic.
     *
     * @param InteractiveLoginEvent $event
     */
    public function onSecurityInteractiveLogin(InteractiveLoginEvent $event) {
        if ($this->securityContext->isGranted('ROLE_SUPER_ADMIN')) {
            
            $departement=$this->em->getRepository('GdsArticleBundle:Departement')->find($this->container->get('request')->get('departement'));
            $user = $event->getAuthenticationToken()->getUser();
            $user->setDepartement($departement);
            $this->em->persist($user);
            $this->em->flush();
        }
       
// do some other magic here
        $user = $event->getAuthenticationToken()->getUser();
// ...
    }

}